package controls.accountsLineChart {
	
	import mx.charts.series.LineSeries;
	import mx.collections.ArrayCollection;
	import mx.collections.XMLListCollection;
	import mx.containers.Panel;
	import mx.controls.Alert;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;	
	
	/**
	 * @author Brent Kersanske
	 */ 
	public class AccountsLineChartClass extends Panel {
		
		[Bindable]
		public var chartTitle:String;
		
		[Bindable]
		public var playerList:XMLListCollection;
		
		[Bindable]
		public var playersService:HTTPService;
		
		[Bindable]
		public var accountsSeries:Array;		
				
		private var _playersFilePath:String;
		
		/**
		 * Constructor.
		 */ 
		public function AccountsLineChartClass(){
			addEventListener(FlexEvent.CREATION_COMPLETE, handleCreationComplete);
		}
		
		/**
		 * 
		 */		
		private function handleCreationComplete(e:FlexEvent):void {
			init();
		}
		
		private function init():void {
		
		}
		
		[Bindable]
		public function set playersFilePath(newPath:String):void {
			_playersFilePath = newPath;
			this.chartTitle  = "";
			updatePlayers();
		}
		
		/**
		 * 
		 */ 
		public function get playersFilePath():String {
			return _playersFilePath;
		}		
		
		/**
		 * 
		 */ 
		public function updatePlayers():void {
			this.playersService.url = this.playersFilePath;
			this.playersService.send();
		}

		/**
		 * 
		 */ 
		public function handleHTTPServiceFault(event:FaultEvent):void {
			playerList.removeAll();
			Alert.show(event.fault.faultString);
		}
		
		/**
		 * 
		 */ 
		public function handlePlayersResult(event:ResultEvent):void {
			var players:XMLList = XML(event.result).player
			this.accountsSeries = generateNewAccountsSeries(players);
		}
		
		/**
		 * 
		 */ 
		private function generateNewAccountsSeries(players:XMLList):Array {			
			var newAccountSeries:Array = new Array;
			for each(var item:XML in players) {
				newAccountSeries.push(generateNewLineSeries(item));
			}	
			return newAccountSeries;	
		}
		
		/**
		 * 
		 */ 
		private function generateNewLineSeries(item:XML):LineSeries {
			var lineSeries:LineSeries = new LineSeries();
			lineSeries.displayName	  = item.@name;
			lineSeries.dataProvider   = createNewLineSeriesDataProvider(item.children());
			lineSeries.yField		  = "accountValue";
			return lineSeries;
		}
		
		private function createNewLineSeriesDataProvider(roundList:XMLList):ArrayCollection {
			var dataProvider:ArrayCollection = new ArrayCollection();
			for each(var round:XML in roundList.round) {
				dataProvider.addItem({roundNumber: round.@number, accountValue: round.@accountValue});
			}	
			return dataProvider;
		}
	}
}